<template>
    <a-tabs
      hideAdd
      v-model="activeKey"
      type="editable-card"
      @edit="onEdit"
      @change="onChange"
      style="height:100%"
    >
    <a-tab-pane class="content-tab" v-for="pane in cpanes" :tab="pane.title" :key="pane.key" :closable="chasTab">
        <keep-alive>
        <router-view :name="pane.route"/>
        </keep-alive>
    </a-tab-pane>
  </a-tabs>

</template>
<script>
import Vue from 'vue'
import {Tabs} from 'ant-design-vue'
Vue.component(Tabs.name, Tabs)
Vue.component(Tabs.TabPane.name, Tabs.TabPane)
export default {
  name: 'contentTabs',
  data () {
    return {
      activeKey: ''
    }
  },
  props: {
    panes: {
      type: Array
    },
    aKey: String
  },
  computed: {
    cpanes: function () {
      return this.panes
    },
    chasTab: function () {
      return this.panes.length > 1
    }
  },
  watch: {
    aKey: {
      handler: function (value) {
        this.activeKey = value
      },
      immediate: true
    }
  },
  methods: {
    onChange (activeKey) {
      this.panes.forEach((pane, i) => {
        if (pane.key === activeKey) {
          this.$router.push({path: pane.path})
          this.$emit('changeTab', activeKey)
        }
      })
    },
    onEdit (targetKey, action) {
      this[action](targetKey)
    },
    remove (targetKey) {
      let activeKey = this.activeKey
      let lastIndex
      this.panes.forEach((pane, i) => {
        if (pane.key === targetKey) {
          if (i === 0) lastIndex = 1
          else lastIndex = i - 1
        }
      })

      // 如果删除的是当前页，就把上一页设置为当前页
      if (lastIndex < this.panes.length && activeKey === targetKey) {
        const pane = this.panes[lastIndex]
        activeKey = pane.key
        this.$router.push({path: pane.path})
      }

      this.$emit('removeTab', targetKey, activeKey)
    }
  }
}
</script>

<style scoped>
.content-tab {
  position:absolute;
  overflow: auto;
  height: 100%;
}
</style>
